/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fleet.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.Fine;
import com.jeeplus.modules.ap.entity.Sl;
import com.jeeplus.modules.ap.service.FineService;
import com.jeeplus.modules.ap.service.SlService;
import com.jeeplus.modules.fee.entity.FeeZzsl;
import com.jeeplus.modules.fee.service.FeeZzslService;
import com.jeeplus.modules.fleet.entity.*;
import com.jeeplus.modules.fleet.service.*;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 车队收支Controller
 * @author 李超辉
 * @version 2018-10-15
 */
@Controller
@RequestMapping(value = "${adminPath}/fleet/wagesDetil")
public class WagesDetilController extends BaseController {

	@Autowired
	private WagesDetilService wagesDetilService;
	@Autowired
	private FeeZzslService feeZzslService;
	@Autowired
	private MotorcadeLogService motorcadeLogService;
	@Autowired
	private MotorcadeCostService motorcadeCostService;
	@Autowired
	private DepreciationService depreciationService;
	@Autowired
	private WagesService wagesService;
	@Autowired
	private SlService slService;
	@Autowired
	private FineService fineService;

	@ModelAttribute
	public WagesDetil get(@RequestParam(required=false) String id) {
		WagesDetil entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = wagesDetilService.get(id);
		}
		if (entity == null){
			entity = new WagesDetil();
		}
		return entity;
	}
	@RequestMapping(value = "cx")
	@ResponseBody
	public String cx(String min,String max,String pro){
		DecimalFormat df = new DecimalFormat("0.00%");
		NumberFormat nf = NumberFormat.getInstance();
		WagesDetil r=new WagesDetil();
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			r.setPro(pro);
		}else{
			if(!UserUtils.getUseroffice().equals("总部")){
				r.setPro(UserUtils.getUseroffice());
			}
		}
		r.setMin(min);
		r.setStatus("已确认");
		r.setMax(max);
		List<WagesDetil> list=wagesDetilService.findList(r);
		double zsr=0.0;
		double zzc=0.0;
		double zsj=0.0;
		for(WagesDetil  re:list){
			zsr+=Double.parseDouble(re.getSr());
			zzc+=Double.parseDouble(re.getZc());
			zsj+=Double.parseDouble(re.getSj());
		}
		double mlr=zsr-zzc-zsj;
		double lrl=mlr/zsr;
		r.setSr(nf.format(zsr).replaceAll(",",""));
		r.setZc(nf.format(zzc).replaceAll(",",""));
		r.setSj(nf.format(zsj).replaceAll(",",""));
		r.setMlr(nf.format(mlr).replaceAll(",",""));
		r.setLrl(df.format(lrl));
		list.add(r);
		Gson g=new Gson();
		return g.toJson(list).toString() ;
	}


	@RequestMapping(value = "getwages")
	@ResponseBody
	public String getwages (String  i){
		WagesDetil wagesDetil=wagesDetilService.get(i);
		Wages w=new Wages();
		w.setPro(wagesDetil.getPro());
		w.setDate(wagesDetil.getDate());
		List<Wages> list=wagesService.findList(w);
		Gson g=new Gson();
		return g.toJson(list).toString() ;
	}
	/**
	 * 车队收支列表页面
	 */
	@RequiresPermissions("fleet:wagesDetil:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fleet/wagesDetilList";
	}
	/**
	 * 车队收支报表
	 */
	@RequestMapping(value = "list1")
	public String list1() {
		return "modules/fleet/1/wagesDetilList";
	}
	/**
	 * 车队收支报表
	 */
	@RequestMapping(value = "list2")
	public String list2() {
		return "modules/fleet/2/wagesDetilList";
	}
	/**
	 * 车队收支报表
	 */
	@RequestMapping(value = "list3")
	public String list3() {
		return "modules/fleet/3/wagesDetilList";
	}
	/**
	 * 车队收支报表
	 */
	@RequestMapping(value = "list4")
	public String list4() {
		return "modules/fleet/4/wagesDetilList";
	}
		/**
	 * 车队收支列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fleet:wagesDetil:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(WagesDetil wagesDetil, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){wagesDetil.setPro(pro);}
		Page<WagesDetil> page = wagesDetilService.findPage(new Page<WagesDetil>(request, response), wagesDetil);
		return getBootstrapData(page);
	}
	/**
	 * 车队收支列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fleet:wagesDetil:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(WagesDetil wagesDetil, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){wagesDetil.setPro(pro);}
		wagesDetil.setStatus("已确认");
		Page<WagesDetil> page = wagesDetilService.findPage(new Page<WagesDetil>(request, response), wagesDetil);
		return getBootstrapData(page);
	}
	/**
	 * 车队收支列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fleet:wagesDetil:list")
	@RequestMapping(value = "data2")
	public Map<String, Object> data2(WagesDetil wagesDetil, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){wagesDetil.setPro(pro);}
		wagesDetil.setStatus("已确认");
		Page<WagesDetil> page = wagesDetilService.findPage1(new Page<WagesDetil>(request, response), wagesDetil);
		return getBootstrapData(page);
	}
	/**
	 * 车队收支列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fleet:wagesDetil:list")
	@RequestMapping(value = "data3")
	public Map<String, Object> data3(WagesDetil wagesDetil, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){wagesDetil.setPro(pro);}
		wagesDetil.setStatus("已确认");
		Page<WagesDetil> page = wagesDetilService.findPage2(new Page<WagesDetil>(request, response), wagesDetil);
		return getBootstrapData(page);
	}
	/**
	 * 车队收支列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fleet:wagesDetil:list")
	@RequestMapping(value = "data4")
	public Map<String, Object> data4(WagesDetil wagesDetil, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){wagesDetil.setPro(pro);}
		wagesDetil.setStatus("已确认");
		Page<WagesDetil> page = wagesDetilService.findPage3(new Page<WagesDetil>(request, response), wagesDetil);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑车队收支表单页面
	 */
	@RequiresPermissions(value={"fleet:wagesDetil:view","fleet:wagesDetil:add","fleet:wagesDetil:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WagesDetil wagesDetil, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){wagesDetil.setPro(pro);
		wagesDetil.setBsc(UserUtils.getbsc());}
		model.addAttribute("wagesDetil", wagesDetil);
		return "modules/fleet/wagesDetilForm";
	}

	/**
	 * 保存车队收支
	 */
	@ResponseBody
	@RequiresPermissions(value={"fleet:wagesDetil:add","fleet:wagesDetil:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(WagesDetil wagesDetil, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, wagesDetil)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		if(wagesDetil.getIsNewRecord()){
			wagesDetil.setStatus("已创建");
		}
		wagesDetilService.save(wagesDetil);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存车队收支成功");
		return j;
	}




	/**
	 * 确认车队收支
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(WagesDetil wagesDetil, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		DecimalFormat df = new DecimalFormat("0.00%");
		NumberFormat nf = NumberFormat.getInstance();
		wagesDetil.setStatus("已确认");
		Sl sl=slService.findUniqueByProperty("pro",UserUtils.getUseroffice());
		sl=slService.get(sl.getId());
		wagesDetil.setSl(sl.getSl());
		double sj=Double.parseDouble(wagesDetil.getSr())*Double.parseDouble(sl.getSl());
		wagesDetil.setSj(nf.format(sj).replaceAll(",",""));
		double zc=Double.parseDouble(wagesDetil.getWx())+Double.parseDouble(wagesDetil.getJy())+Double.parseDouble(wagesDetil.getLq())+Double.parseDouble(wagesDetil.getZs())+Double.parseDouble(wagesDetil.getQt())+Double.parseDouble(wagesDetil.getGz())+Double.parseDouble(wagesDetil.getZj());
		zc+=Double.parseDouble(wagesDetil.getFhf())+Double.parseDouble(wagesDetil.getCpsh())+Double.parseDouble(wagesDetil.getLtf());

		wagesDetil.setZc(nf.format(zc).replaceAll(",",""));
		double mlr=Double.parseDouble(wagesDetil.getSr())-zc-sj;
		wagesDetil.setMlr(nf.format(mlr).replaceAll(",",""));
		double lrl=mlr/Double.parseDouble(wagesDetil.getSr());
		wagesDetil.setLrl(df.format(lrl));
		wagesDetilService.save(wagesDetil);
		j.setMsg("确认车队收支成功");
		return j;
	}
	/**
	 * 取消确认车队收支
	 */
	@ResponseBody
	@RequestMapping(value = "qxqr")
	public AjaxJson qxqr(WagesDetil wagesDetil, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		wagesDetil.setStatus("已创建");
		wagesDetil.setSl("");
		wagesDetil.setSj("");
		wagesDetil.setMlr("");
		wagesDetil.setLrl("");
		wagesDetilService.save(wagesDetil);
		j.setMsg("取消确认车队收支成功");
		return j;
	}

	/**
	 * 手动计算上月数据
	 */
	@ResponseBody
	@RequestMapping(value = "sd")
	public AjaxJson sd() {
		WagesDetil detil=new WagesDetil();
		AjaxJson j = new AjaxJson();
		DecimalFormat df = new DecimalFormat("0.00%");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		NumberFormat nf = NumberFormat.getInstance();
		Date d=new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.MONTH, -1);
		d=c.getTime();
		detil.setDate(d);
		detil.setPro(UserUtils.getUseroffice());
		List<WagesDetil> list=wagesDetilService.findList(detil);
		if(list!=null&&list.size()>0){
			j.setSuccess(false);
			j.setMsg("请勿重复计算");
			return j;
		}


		//收入
		MotorcadeLog m=new MotorcadeLog();
		m.setProjectName(UserUtils.getUseroffice());
		m.setDate(d);
		List<MotorcadeLog> mos=motorcadeLogService.findList(m);
		int ts=0;
		double sr=0.0;
		for(MotorcadeLog mo:mos){
			ts+=Integer.parseInt(mo.getCount());
			sr+=Double.parseDouble(mo.getMoney());
		}
		detil.setTs(ts+"");
		detil.setSr(sr+"");
		//支出
		MotorcadeCost co=new MotorcadeCost();
		co.setProjectName(UserUtils.getUseroffice());
		co.setDate(d);
		List<MotorcadeCost> costs=motorcadeCostService.findList(co);
		double wxf=0.0;
		double zsf=0.0;
		double lqf=0.0;
		double jyf=0.0;
		double qt=0.0;
		double ltf=0.0;
		double fhf=0.0;
		double cpsh=0.0;
		for(MotorcadeCost mo:costs){
			if(mo.getDisbursementType().equals("维修费")){
				wxf+=Double.parseDouble(mo.getCost());
			}
			if(mo.getDisbursementType().equals("加油费")){
				jyf+=Double.parseDouble(mo.getCost());
			}
			if(mo.getDisbursementType().equals("住宿费")){
				zsf+=Double.parseDouble(mo.getCost());
			}
			if(mo.getDisbursementType().equals("路桥费")){
				lqf+=Double.parseDouble(mo.getCost());
			}
			if(mo.getDisbursementType().equals("其它费用")){
				qt+=Double.parseDouble(mo.getCost());
			}
			if(mo.getDisbursementType().equals("轮胎费")){
				ltf+=Double.parseDouble(mo.getCost());
			}
			if(mo.getDisbursementType().equals("防护费")){
				fhf+=Double.parseDouble(mo.getCost());
			}
			if(mo.getDisbursementType().equals("产品损耗")){
				cpsh+=Double.parseDouble(mo.getCost());
			}
		}
		detil.setWx(wxf+"");
		detil.setJy(jyf+"");
		detil.setZs(zsf+"");
		detil.setLq(lqf+"");
		detil.setQt(qt+"");
		detil.setLtf(ltf+"");
		detil.setFhf(fhf+"");
		detil.setCpsh(cpsh+"");
		//折旧
		Depreciation de=new Depreciation();
		de.setPro(UserUtils.getUseroffice());
		de.setMin(d);
		de.setMax(d);
		List<Depreciation> ll=depreciationService.findList(de);
		double zj=0.0;
		for(Depreciation ca:ll){
			zj+=Double.parseDouble(ca.getDepreciation());
		}
		detil.setZj(zj+"");
		//罚款
		Fine fine=new Fine();
		fine.setDate(d);
		fine.setPro(UserUtils.getUseroffice());
		List<Fine> fines=fineService.findList(fine);
		double fk=0.0;
		for(Fine fi:fines){
			fk+=Double.parseDouble(fi.getZxje());
		}
        detil.setFk(nf.format(fk).replaceAll(",",""));
		//工资
		Wages w=new Wages();
		w.setDate(d);
		w.setPro(UserUtils.getUseroffice());
		List<Wages> was=wagesService.findList(w);
		double gz=0.0;
		for(Wages wa:was){
			gz+=Double.parseDouble(wa.getGz())+Double.parseDouble(wa.getSb());
		}
		detil.setGz(gz+"");
		detil.setBsc(UserUtils.getbsc());
		detil.setStatus("已创建");
		wagesDetilService.save(detil);
		j.setMsg("计算成功");
		return j;
	}
	/**
	 * 删除车队收支
	 */
	@ResponseBody
	@RequiresPermissions("fleet:wagesDetil:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(WagesDetil wagesDetil, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		wagesDetilService.delete(wagesDetil);
		j.setMsg("删除车队收支成功");
		return j;
	}
	
	/**
	 * 批量删除车队收支
	 */
	@ResponseBody
	@RequiresPermissions("fleet:wagesDetil:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			wagesDetilService.delete(wagesDetilService.get(id));
		}
		j.setMsg("删除车队收支成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fleet:wagesDetil:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(WagesDetil wagesDetil, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "车队收支"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WagesDetil> page = wagesDetilService.findPage(new Page<WagesDetil>(request, response, -1), wagesDetil);
    		new ExportExcel("车队收支", WagesDetil.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出车队收支记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fleet:wagesDetil:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WagesDetil> list = ei.getDataList(WagesDetil.class);
			for (WagesDetil wagesDetil : list){
				try{
					wagesDetilService.save(wagesDetil);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条车队收支记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条车队收支记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入车队收支失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fleet/wagesDetil/?repage";
    }
	
	/**
	 * 下载导入车队收支数据模板
	 */
	@RequiresPermissions("fleet:wagesDetil:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "车队收支数据导入模板.xlsx";
    		List<WagesDetil> list = Lists.newArrayList(); 
    		new ExportExcel("车队收支数据", WagesDetil.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fleet/wagesDetil/?repage";
    }

}